import 'dart:convert';

import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:safetymonitor/app/data/entities/application/get_realtime_person_monitoring_entity.dart';

class DynamicTrajectoryController extends GetxController {
  final GetRealtimePersonMonitoringPersonLocationDataDO getRealtimePersonMonitoringPersonLocationDataDO =Get.arguments as GetRealtimePersonMonitoringPersonLocationDataDO;

  URLRequest? url;
  InAppWebViewController? inAppWebViewController;


  @override
  void onInit() {
    super.onInit();
    // 设置首选的方向为横屏
    // ScreenControlUtils.setting();
    // getRealtimePersonMonitoring();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky, overlays: []);
  }
  /// 获取 人员实时监测（含人员定位信息 经纬度）
  // Future<GetRealtimePersonMonitoringPersonLocationDataDO?> getRealtimePersonMonitoring() async {
  //   final resp = await HttpUtil().generateGetRequest<GetRealtimePersonMonitoringEntity>(
  //     Interface.getRealtimePersonMonitoring,
  //     queryParameters: {
  //       'id':Get.arguments,
  //     },
  //   ).execute(isShowToast: false);
  //   if (resp.isSucceed && resp.data != null) {
  //     final GetRealtimePersonMonitoringEntity? object = resp.data;
  //     return  object?.personLocationDataDO.first;
  //       // longitude = firstPersonLocationDataDO?.personTrackDO.longitude;
  //       // latitude = firstPersonLocationDataDO?.personTrackDO.latitude;
  //   }
  //   return null;
  // }
  @override
  void onClose() {
    inAppWebViewController?.dispose();
    super.onClose();
  }

  ///初始化数据
  initDate() {
       url = URLRequest(url: WebUri('${Interface.plotMapAddress}//#/nest?func=3dDisplay&_t=1712826013832'));
    // url = URLRequest(url: WebUri('http://192.168.50.131:30012/#/nest?func=3dDisplay&_t=1712826013832'));
    // url = URLRequest(url: WebUri('http://192.168.50.131:30012/#/nest?func=3dDisplay&_t=1712826013832&scale=0'));
  }

  /// 数据初始化
  _postData() async {
    final data = {
      'type': 'DataInit',
      'data': {
        'group': 'default',
        'data': [
          {
            'UIMode': '',
            'configs': {
              'width': 5,
              'ground': false,
              'color': [0, 0, 1, 1]
            },
            'id': 'bbcd1238-aacc-3652-56ad-205ccfe25ad36df1',
            'mode': 'Line',
            'name': '折线',
            'options': {},
            'positions': [
              [1.8530639859151827, 0.5622286129483111, 446.5617771720005],
              [1.8531749571298854, 0.5621935754044496, 437.157911543327],
              [1.8532849199495545, 0.5621500160266254, 440.7667009817055],
              [1.8533606669542368, 0.5621172083031845, 418.5505116020397],
              [1.8533287330627952, 0.5622009648876174, 417.5998763424102],
              [1.8532815415406612, 0.562213362845909, 417.85899726780985],
              [1.8532297574101988, 0.5622139724445525, 418.00557163438214],
              [1.853183387732425, 0.562210601397865, 419.79313711032836],
              [1.8531650073398975, 0.5622368444783143, 419.7270150899306],
              [1.8531478188792019, 0.562284372899488, 420.9522419467134],
              [1.8531240989156792, 0.5622906481020712, 421.9035484607923],
              [1.8530945622531374, 0.5622812676995226, 422.80063817963423],
              [1.8530582387895447, 0.5622669232860149, 430.22750521319284],
              [1.8530157701889423, 0.5622596479982619, 428.4668716538621],
              [1.852972665153191, 0.5622570330130235, 427.77806307353836]
            ],
            'type': 'GeoPolyline'
          },
        ]
      }
    };
    await Future.delayed(const Duration(seconds: 2));
    _sendMessage(data);
  }

  /// 发送消息
  Future<void> _sendMessage(data) async {
    print('_sendMessage：${jsonEncode(data)}');
    await inAppWebViewController?.postWebMessage(message: WebMessage(data: jsonEncode(data)));
  }

  /// webview加载完成后
  onWebViewCreated(InAppWebViewController controller) async {
    inAppWebViewController = controller;
    // 先加载地形
    await _loadTerrain('http://203.25.217.225:38080/model/SCDiXing/yibin');
    // 加载瓦片
    await _loadTileset('http://203.25.217.39:81/model/SiChuan/YiBin/P-YB003/tileset.json');
    // await _setBaseURL();
    // // 配置api请求地址

    // await _setApiUrl();
    //二维数组 后端接口返回 发送给h5
    // final String jsonEncodedArray = jsonEncode(twoDimensionalArray);

    // 数据初始化
    // await _postData();
    //元素定位
    await _dataFlyTo(getRealtimePersonMonitoringPersonLocationDataDO);
    // //数据显示（隐藏）
    // await _dataDisplay();
    // //标绘数据的格式
    // await _busDataInit();
  }

  // 加载地形地址
  _loadTerrain(String url) async {
    final data = {
      'type': 'Terrain',
      'data': {
        'url': url,
      }
    };
    await Future.delayed(const Duration(seconds: 2));
    _sendMessage(data);
  }

  /// 加载瓦片地址
  _loadTileset(String tilesetUrl) async {
    final data = {
      'type': 'Tileset',
      'data': {
        'url': tilesetUrl,
      }
    };
    await Future.delayed(const Duration(seconds: 2));
    _sendMessage(data);
  }

  void onLoadStart(InAppWebViewController controller, WebUri? url) {
    print('Page started loading: $url');
  }

  void onLoadStop(InAppWebViewController controller, WebUri? url) {
    print('Page finished loading: $url');
  }

  void onConsoleMessage(InAppWebViewController controller, ConsoleMessage consoleMessage) {
    print('Console message: ${consoleMessage.message}');
  }

  _setApiUrl() async {
    final data = {
      'type': 'setApiUrl',
      'data': {
        'get': {
          url: '/admin-api/system/plotting-base-info/getJsonData',
        },
      }
    };
    await Future.delayed(const Duration(seconds: 2));
    _sendMessage(data);
  }

  _setBaseURL() async {
    final data = {
      'type': 'setBaseURL',
      'data': {
        url: 'http://10.3.18.6:48081',
      }
    };
    await Future.delayed(const Duration(seconds: 2));
    _sendMessage(data);
  }

  /// 元素定位
  _dataFlyTo(GetRealtimePersonMonitoringPersonLocationDataDO? getRealtimePersonMonitoringPersonLocationDataDO) async {
    // final data = {
    //   'type': 'DataFlyTo',
    //   'data': {
    //     'key': 'bbcd1238-aacc-3652-56ad-205ccfe25ad36df1',
    //   }
    // };
   final data = {
      'type': 'CameraFlyTo',
      'data':  {
        'position': [
          getRealtimePersonMonitoringPersonLocationDataDO?.personTrackDO.longitude,
          getRealtimePersonMonitoringPersonLocationDataDO?.personTrackDO.latitude,
          1500
        ],
        'viewDistance': 200,
        'positionIsRadian': true,
        'rotation': [
          0,
          -1.0471975511965976,
          0
        ]
      }
    };
    await Future.delayed(const Duration(seconds: 2));
    _sendMessage(data);
  }

  ///数据显示（隐藏）
  _dataDisplay() async {
    final data = {
      'group: ': 'DataDisplay',
      'data': {
        'group': 'default',
        'show': true,
      }
    };
    // await Future.delayed(const Duration(seconds: 2));
    _sendMessage(data);
  }

  ///标绘数据的格式
  _busDataInit() async {
    final data = {
      "type": "BusDataInit",
      "data": {
        "data": [
          {
            "id": "DeviceLocation_56",
            "companyId": 100,
            "dataId": "DeviceLocation_56",
            "iconType": "PinCommon",
            "name": "ddwdw",
            "configs": "%7B%7D",
            "options": "%7B%7D",
            "dataUrl": "",
            "threeDimensionalUrl": "",
            "createTime": 1712736166000
          },
          {
            "id": "DeviceLocation_55",
            "companyId": 100,
            "dataId": "DeviceLocation_55",
            "iconType": "PinCommon",
            "name": "csdcsd",
            "configs": "",
            "options": "",
            "dataUrl": "",
            "threeDimensionalUrl": "",
            "createTime": 1712736183000
          }
        ],
        "group": "DeviceLocation",
        "cacheKey": "",
        "isCallback": true
      }
    };
    // await Future.delayed(const Duration(seconds: 2));
    _sendMessage(data);
  }
}
